package com.yc.web.servlets;


import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import com.yc.web.model.JsonModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@WebServlet("/FileToOSSText.action")
@MultipartConfig(fileSizeThreshold = 1024*1024 , maxFileSize = 1024*1024*5 , maxRequestSize = 1024*1024*5*5)
public class FileToOSSText extends BaseServlet {

    public void regFile(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        JsonModel jm = new JsonModel();
        Collection<Part> parts = req.getParts(); // 获取所有部分
        System.out.println("getParts:"+req.getParts());
        try {
            for (Part part : parts) {
                if (part.getContentType() != null) { // 检查部分是否为文件
                    String fileName = part.getSubmittedFileName(); // 获取文件名
                    InputStream fileContent = part.getInputStream(); // 获取文件内容的输入流
                    String url = UploadToOSS.uploadFileOSS( fileName ,  fileContent );//调用上传到OSS的函数

                    if ( "0".equals( url ) ){  //上传失败
                        jm.setCode(0);
                        jm.setError("上传失败。。。");
                        super.writeJson( jm , resp );
                        return;
                    }else {     //上传成功
                        jm.setObj( url );//访问域名
                        jm.setCode(1); //表示成功
                    }
                }
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {
            super.writeJson(jm,resp);
            System.out.println("OSS close Success");
            UploadToOSS.close(); // 最终，无论上传成功还是失败，都关闭OSS客户端实例以释放资源。
            HttpSession session= req.getSession();
            int sid= (int) session.getAttribute("goodsid");
            System.out.println("上面的sid为"+sid);
            String url= (String) jm.getObj();
            String sql="insert into ShoePhotos(sid,photourl,ismain)values(?,?,'true')";
            String sql2="DELETE FROM ShoePhotos WHERE sid = ? AND ismain = 'true'";
            int result1=db.doUpdate(sql2,sid);
            int result2 =db.doUpdate(sql,sid,url);
            System.out.println("结果1"+result1);
            System.out.println("结果2"+result2);
        }}
    public void getsid(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, InvocationTargetException, InstantiationException, IllegalAccessException, JSONException {
        BufferedReader reader = request.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String jsonData = sb.toString();
        System.out.println(jsonData);
        // 解析 JSON 字符串
        JSONObject jsonObject = new JSONObject(jsonData);

        // 获取 sid 的值
        int sid = jsonObject.getInt("sid");
        HttpSession session=request.getSession();
        session.setAttribute("goodsid",sid);
        System.out.println("sid 的值是: " + sid);
        String sql="DELETE FROM ShoePhotos\n" +
                "                WHERE photourl IS  NULL\n" +
                "                or photourl like '0'\n" +
                "                AND ismain LIKE 'false';";
        int result= db.doUpdate(sql);
        String sql2="SELECT *\n" +
                "FROM ShoePhotos\n" +
                "WHERE ismain like false AND photourl IS NULL";
        List list=db.select(sql2);
        if (list.size()<=0){
            System.out.println("初始化副图成功");
        }
        String sql3="DELETE n1 FROM ShoePhotos n1, ShoePhotos n2 \n" +
                "WHERE n1.photoid > n2.photoid \n" +
                "AND n1.sid = n2.sid \n" +
                "AND n1.photourl = n2.photourl\n" +
                "AND n1.ismain = n2.ismain";
        int result3= db.doUpdate(sql3);
        System.out.println("删除的行数"+result);
        System.out.println(" 重复的列的数量为"+result3);

    }
    public void addmore(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        JsonModel jm = new JsonModel();
        Collection<Part> parts = req.getParts(); // 获取所有部分
        System.out.println("getParts:"+req.getParts());
        List urllist=new ArrayList<>();
        try {

            for (Part part : parts) {
                if (part.getContentType() != null) { // 检查部分是否为文件
                    String fileName = part.getSubmittedFileName(); // 获取文件名
                    InputStream fileContent = part.getInputStream(); // 获取文件内容的输入流
                    String url = UploadToOSS.uploadFileOSS( fileName ,  fileContent );//调用上传到OSS的函数
                    urllist.add(url);
                    if ( "0".equals( urllist ) ){  //上传失败
                        jm.setCode(0);
                        jm.setError("上传失败。。。");
                        super.writeJson( jm , resp );
                        return;
                    }else {     //上传成功
                        // jm.setObj( urllist );//访问域名
                        jm.setCode(1); //表示成功
                        System.out.println("看我调用了几次");
                        HttpSession session= req.getSession();
                        int sid= (int) session.getAttribute("goodsid");
                        String resulturl = (String) jm.getObj();
                        String sql="insert into ShoePhotos(sid,photourl,ismain)values(?,?,'false')";
                        int result=db.doUpdate(sql,sid,url);
                        System.out.println("上传的副图数为"+result);
                    }
                }
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {
            jm.setObj(urllist.toString());
            System.out.println("最终方法调用了几次");
            super.writeJson(jm,resp);
            System.out.println("OSS close Success");
            UploadToOSS.close(); // 最终，无论上传成功还是失败，都关闭OSS客户端实例以释放资源。
        }
        System.out.println(urllist);
    }
}
